#
# object.py -- generic physical object
# 
# author: Tom "Knio" Flanagan
#         knio@h4xn3t.net
#         theknio@gmail.com
#         irc.freenode.net - Knio - #python #pygame #py
#
# this file released under Public Domain
#

from constants import *


class Vector:
    def __init__(self, *args, **kwargs):
        self.x = 0.
        self.y = 0.
        self.s = 0.
        self.a = 0.
        self.h = 0.
        self.f = 0.
        if args:
            if isinstance(args[0], Vector): self.__dict__.update(args[0].vector())
            else:
                self.x = args[0]
                if len(args) >= 2: self.y = args[1]
        self.__dict__.update(kwargs)

    def vector(self):
        return dict([(k, v) for k, v in self.__dict__.items() if k in ['x', 'y', 's', 'h', 'f', 't']])
       
    def angle(self, obj):
        x = self.x - obj.x
        y = self.y - obj.y
        return -math.atan2(y,-x)

    def distance(self, obj):
        x = self.x - obj.x
        y = self.y - obj.y
        return math.sqrt(x**2 + y**2)

    def direction(self, angl):
        direction = (self.f - angl) % CI
        if direction >  PI: direction -= CI
        if direction < -PI: direction += CI
        return -direction

    def coordinates(self, h, d):
        vec = Vector(**self.vector())
        vec.x += math.cos(h) * d
        vec.y += math.sin(h) * d
        return vec




class Object(Vector):
    id = 0
    def __init__(self, battle, **kwargs):
        self.battle = battle
        self.x = 0.
        self.y = 0.
        self.s = 0.
        self.a = 0.
        self.h = 0.
        self.f = 0.
        self.t = 0.
        self.team = 0
        self.size = 1
        self.state = 1
        self.data = []
        self.id = Object.id
        Object.id += 1
        
        self.sprite = 'images/default.bmp'
        self.color = '0xFFFFFF'
        self.view = None

        self.battle.add(self)
        self.__dict__.update(kwargs)

    def tick(self, data):
        self.data = data
        if self.state: self.poll()

    def poll(self):
        pass

    def move(self):
        if (abs(self.x) > self.battle.size*2) or (abs(self.y) > self.battle.size*2):
            self.battle.remove(self)
            return
        self.s *= (1-self.s/self.battle.friction)
        vect = self.coordinates(self.h, self.s)
        vect = vect.coordinates(self.f, self.a)
        self.f += self.t
        self.s = self.distance(vect)
        self.h = self.angle(vect)
        self.x = vect.x
        self.y = vect.y

    def hit(self, weapon, damage):
        pass

    def die(self, damage):
        self.state = 0
        self.a = 0
